package com.vjwealth.android.nos.adapter

import android.content.Context
import android.support.v4.view.PagerAdapter
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

/**
 * projectName KNOS
 * date 2017/9/29
 * description com.vjwealth.android.nos.adapter
 */
abstract class ViewPagerAdapter<T>(context: Context,
                          layoutResId: Int,
                          list: List<T>) : PagerAdapter() {
    var mContext: Context
    var mLayoutInflater: LayoutInflater
    var mLayoutResId: Int
    var mDataList: List<T>
    var mViewList: SparseArray<View>

    init {
        mContext = context
        mLayoutInflater = LayoutInflater.from(context)
        mLayoutResId = layoutResId
        mDataList = list
        mViewList = SparseArray()
    }
    override fun isViewFromObject(view: View?, obj: Any?): Boolean {
        return view == obj
    }

    override fun getCount(): Int {
        return mDataList.size
    }

    override fun instantiateItem(container: ViewGroup?, position: Int): Any {
        var t: T = mDataList.get(position)
        var view: View? = mViewList.get(position)
        if(view == null){
            view = mLayoutInflater.inflate(mLayoutResId, null, false)
            mViewList.put(position, view)
        }
        convert(view!!, position, t)
        container!!.addView(view)
        return view
    }

    override fun destroyItem(container: ViewGroup?, position: Int, obj: Any?) {
        container!!.removeView(obj as View?)
    }

    abstract fun convert(view: View, position: Int, t: T)
}